//
//  HYYHomeViewController.swift
//  Hyy9Weibo
//
//  Created by Air on 16/3/22.
//  Copyright © 2016年 hyy. All rights reserved.
//

import UIKit

class HYYHomeViewController: HYYBaseViewController {

    //MARK: - 属性
    private let reuseIdentifier = "ReuseIdentifier"
    //微博数据
    var statuses:[HYYStatus]?{
        didSet{
            self.tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //登陆以后才做后面操作
        if !HYYUserAccountModel.sharedInstance.userLogin{
            return
        }
        
        //设置导航栏
        setupNavigationBar()
        setupTitleButton()
        prepareTableView()
        //使用VM加载数据
        HYYStatusViewModel.shardInstances.loadStatus { (statuses, error) in
            if error != nil{
                HYYPrint(msg: "加载微博数据出错: \(error)")
                return
            }
            //加载微博数据成功，并且字典转模型完成，statuses放的是微博模型数组
            print("加载微博数据成功:\(statuses)")
            //当获取到数据后，将数据赋值给控制器属性，让tableview来根据statuses显示cell
            self.statuses = statuses
        }
        
    }
    
    private func prepareTableView(){
        //注册cell
        tableView.registerClass(HYYStatusCell.self, forCellReuseIdentifier: reuseIdentifier)
        //cell的高度根据cell里面的子控件来自动布局来确定高度
        //0.添加预估行高
        //1.rowHeight = UITableViewAutomaticDimension
        //cell里面的约束要确定好 .contenVeiw的高度要根据子控件来,最终cell的高度会根据contenview高度来
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableViewAutomaticDimension
        //取消cell之间的分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    //设置导航栏Title
    private func setupTitleButton(){
        let name = HYYUserAccountModel.sharedInstance.userAccount?.screen_name
        let titleButton = HYYHomeTitleButton(title: name, imageName: "navigationbar_arrow_down")
        titleButton.addTarget(self, action: #selector(HYYHomeViewController.didClickTitleButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleButton
    }
    
    //设置导航栏左右
    private func setupNavigationBar(){
//        let leftButton = UIButton()
//        leftButton.setImage(UIImage(named: "navigationbar_friendsearch"), forState: UIControlState.Normal)
//        leftButton.setImage(UIImage(named: "navigationbar_friendsearch_highlighted"), forState: UIControlState.Highlighted)
//        leftButton.sizeToFit()
//        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)
//        
//        let rightButton = UIButton()
//        rightButton.setImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal)
//        rightButton.setImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Highlighted)
//        rightButton.sizeToFit()
//        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)

//        navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_friendsearch")
//        navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_pop")
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: #selector(HYYHomeViewController.didClickLeftItem))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(HYYHomeViewController.didClickRightItem))
    }
    
    
    //MARK: - 按钮点击事件
    
    @objc private func didClickTitleButton(button:HYYHomeTitleButton)  {
        
        //当点击按钮的时候selected取反
        button.selected = !button.selected
        
        //按钮选中的时候箭头朝上,不选中朝下
        //uiview旋转动画特点：1.两边一样远，顺时针，2.哪边近走哪边
//        if button.selected {
//            UIView.animateWithDuration(HYYDefaultDuration, animations: { 
//                button.imageView?.transform = CGAffineTransformMakeRotation(CGFloat(M_PI-0.001))
//            })
//        }else{
//            UIView.animateWithDuration(HYYDefaultDuration, animations: { 
//                button.imageView?.transform = CGAffineTransformIdentity
//            })
//        }
        
        UIView.animateWithDuration(HYYDefaultDuration) { 
            button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI-0.001)) : CGAffineTransformIdentity
        }
        
        if button.selected {
            let popoverVC = HYYPopoverViewController()
            
            //iOS 8以后popoverPresentationController
            //设置modal的显示样式
            popoverVC.modalPresentationStyle = .Popover
            //设置popoverPresentationController的代理，实现代理方法，来让popover不要适配iphone
            popoverVC.popoverPresentationController?.delegate = self
            //popover的箭头指向titleview，默认指向左上角
            popoverVC.popoverPresentationController?.sourceView = navigationItem.titleView
            //设置sourceView.bounds给sourceRect
            popoverVC.popoverPresentationController?.sourceRect = (navigationItem.titleView?.bounds)!
            //设置popover的大小
            popoverVC.preferredContentSize = CGSize(width: 180, height: 44 * popoverVC.titles.count)
            //弹出
            presentViewController(popoverVC, animated: true, completion: nil)
            
        }
        
    }
    
    func didClickLeftItem(){
        HYYPrint(msg: "didClickLeftItem")
    }
    
    func didClickRightItem() {
        HYYPrint(msg: "didClickRightItem")
    }
    
    /**
     创建一个带按钮的uibarbuttonitem
     
     - parameter imageName: 图片名称
     
     - returns: UIBarButtonItem
     */
//    func createBarButtonItem(imageName:String) -> UIBarButtonItem {
//        let button = UIButton()
//        button.setImage(UIImage(named: "\(imageName)"), forState: UIControlState.Normal)
//        button.setImage(UIImage(named: "\(imageName)_highlighted"), forState: UIControlState.Highlighted)
//        button.sizeToFit()
//        return UIBarButtonItem(customView: button)
//    }

}

//MARK: - 扩展HYYHomeViewController，将tabelview相关方法都写在这个扩展里
extension HYYHomeViewController{
    
    //返回多少个cell
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //statuses?: statuses = nil
        //??:表示？？前面的可选如果没有值，就用？？后面的
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HYYStatusCell
        
        //设置cell的内容
//        cell.textLabel?.text = statuses?[indexPath.row].text
        cell.status = statuses?[indexPath.row]
        HYYPrint(msg: statuses?[indexPath.row].user?.screen_name)
        
        return cell
        
    }
    
    //取消cell的选中
//    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//        tableView.deselectRowAtIndexPath(indexPath, animated: false)
//    }
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        //cell不要高亮
        return false
    }
}


//MARK: - 扩展HYYHomeViewController实现UIPopoverPresentationControllerDelegate协议
extension HYYHomeViewController:UIPopoverPresentationControllerDelegate{
    //不让popover适配iphone，默认适配就是全屏
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    
    //popover已经关闭的时候调用
//    func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
//        //让箭头转下来
//        let titleButton = navigationItem.titleView as! HYYHomeTitleButton
//        didClickTitleButton(titleButton)
//    }
    
    //系统询问是否popover是否需要关闭
    func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
        let titleButton = navigationItem.titleView as! HYYHomeTitleButton
        didClickTitleButton(titleButton)
        return true
    }
}
